#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;

using System.Web;

using System.Collections;
using WaveMaster.Holidays.Club.Domain;
using WaveMaster.Holidays.Club.Service;

#endregion

namespace WaveMaster.Holidays.Club.Web
{
    public partial class TicketDeductionForm : Form
    {
        TicketDeduction m_ticketDeduction;
        User m_current_user;
        EditMode m_editmode;
        TicketDeductionService m_ticketDeductionService;
        MemberTypeService m_MemberTypeService;
        TravelAgentService m_TravelAgentService;
        MainForm m_mainForm;
        CheckInService m_bookingService;
        UserControlTicketDeduction m_parentForm;

        public TicketDeductionForm(string name, TicketDeduction tktdedution, User currentUser, MainForm mainForm, UserControlTicketDeduction parentForm, EditMode editmode)
        {
            InitializeComponent();
            m_ticketDeductionService = (TicketDeductionService)ServiceFactory.Instance().GetService(ServiceFactory.TICKET_DEDUCTION_SERVICE);
            m_TravelAgentService = (TravelAgentService)ServiceFactory.Instance().GetService(ServiceFactory.TRAVEL_AGENT_SERVICE);
            m_MemberTypeService = (MemberTypeService)ServiceFactory.Instance().GetService(ServiceFactory.MEMBER_TYPE_SERVICE);
            m_bookingService = (CheckInService)ServiceFactory.Instance().GetService(ServiceFactory.BOOKING_SERVICE);
            m_current_user = currentUser;
            m_mainForm = mainForm;
            this.Name = name;
            m_parentForm = parentForm;
            m_ticketDeduction = tktdedution;
            initButtonEvent();
            initComboDataSource();
            setEditMode(editmode);
            if (tktdedution.m_deductID == 0)
            {
                clearForm();
            }
            else
            {
                m_ticketDeduction = m_ticketDeductionService.GetTicketDeductionByID(tktdedution.m_deductID);
                loadUser(); 
                enableForm(editmode == EditMode.Edit);
            }
            
            //enableForm(false);
            initTimeAvailable();
            dateTimePickerDate.MinDate = DateTime.Today;
        }

        private void initTimeAvailable()
        {
            timerUpdateBalance.Interval = 3000;
            timerUpdateBalance.Tick += new EventHandler(timerUpdateBalance_Tick);
            timerUpdateBalance.Start(); 
            timerUpdateBalance_Tick(null, null);
        }

        void timerUpdateBalance_Tick(object sender, EventArgs e)
        {
            try
            {
                TravelAgent travelagent = (TravelAgent)comboBoxTravelAgent.SelectedValue;
                decimal availableOneWay = m_bookingService.GetAvailableBook(travelagent.TravelAgentID, TicketType.OneWay);
                decimal availableTwoWay = m_bookingService.GetAvailableBook(travelagent.TravelAgentID, TicketType.TwoWay);
                labelOneway.Text = availableOneWay.ToString();
                labelTwoWay.Text = availableTwoWay.ToString();
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message, "Error Exception", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }
        }

        private void clearForm()
        {
            textBoxUserCode.Text = "AUTONUMBER";
            comboBoxTravelAgent.Text = m_current_user.TravelAgent.Name;
            dateTimePickerDate.Value = DateTime.Today;
            //comboBoxTravelAgent.SelectedIndex = 0;
            comboBoxTicketType.Text = TicketType.TwoWay.ToString();
            numericUpDownQuantity.Value =1;
            textBoxREmark.Text = "";
            m_ticketDeduction = new TicketDeduction();
            clearErrorProvider();
            enableForm(true);
            setEditMode(EditMode.Create);
            textBoxUserCode.SelectAll();
            //comboBoxTravelAgent.Focus();
        }

        private void initButtonEvent()
        {
            //toolBarButtonClear.Click += new EventHandler(toolBarButtonClear_Click);
            toolBarButtonSave.Click += new EventHandler(toolBarButtonSave_Click);
            //toolBarButtonDelete.Click += new EventHandler(toolBarButtonDelete_Click);
            toolBarButtonRefresh.Click += new EventHandler(toolBarButtonRefresh_Click);
            toolBarButtonEdit.Click += new EventHandler(toolBarButtonEdit_Click);
            //toolBarButtonSearch.Click += new EventHandler(toolBarButtonSearch_Click);
            toolBarButtonCancel.Click += new EventHandler(toolBarButtonCancel_Click);
        }
              
        void toolBarButtonEdit_Click(object sender, EventArgs e)
        {
            setEditMode(EditMode.Edit);
            enableForm(!toolBarButtonEdit.Enabled);
        }

        void toolBarButtonCancel_Click(object sender, EventArgs e)
        {
            if (m_editmode == EditMode.Load)
                this.Close();
            else
            MessageBox.Show("Are you sure to cancel?", "Confirmation", MessageBoxButtons.YesNo,
               MessageBoxIcon.Question, new EventHandler(cancelConfirmation));
        }

        void cancelConfirmation(object sender, EventArgs e)
        {
             MessageBoxWindow msg = (MessageBoxWindow)sender;
             if (msg.DialogResult == DialogResult.Yes)
             {
                 this.Close();
             }
        }
        private void initComboDataSource()
        {
            comboBoxTravelAgent.DataSource = m_TravelAgentService.LoadAllTravelAgent();
            comboBoxTicketType.DataSource = Enum.GetValues(typeof(TicketType));
        }

        void toolBarButtonRefresh_Click(object sender, EventArgs e)
        {
            //loadAllUser();
            initComboDataSource();
            if (m_editmode == EditMode.Load || m_editmode == EditMode.Edit)
                loadUser();
        }

        private void clearErrorProvider()
        {
            errorProviderUser.SetError(textBoxUserCode, "");
            errorProviderUser.SetError(numericUpDownQuantity, "");
            errorProviderUser.SetError(comboBoxTravelAgent, "");
        }
        private bool isValidForm()
        {
            clearErrorProvider();
            decimal available = 0;
            TicketType tt = (TicketType)Enum.Parse(typeof(TicketType), comboBoxTicketType.Text);
            TravelAgent travelagent = (TravelAgent)comboBoxTravelAgent.SelectedValue;
            available = m_bookingService.GetAvailableBook(travelagent.TravelAgentID, tt);
            if (m_ticketDeduction.m_deductID > 0)
            {
                if (m_ticketDeduction.m_travelAgent.TravelAgentID == travelagent.TravelAgentID)
                    available += m_ticketDeduction.m_quantity;
            }
            bool valid_a = textBoxUserCode.Text != string.Empty;
            bool valid_b = numericUpDownQuantity.Value != 0;
            bool valid_c = numericUpDownQuantity.Value <= available;
            bool valid_d = comboBoxTravelAgent.SelectedItem != null;
            if (!valid_a) errorProviderUser.SetError(textBoxUserCode, "Code can not be empty");
            if (!valid_b) errorProviderUser.SetError(numericUpDownQuantity, "Quantity can not be empty");
            if (!valid_c) errorProviderUser.SetError(numericUpDownQuantity, "Quantity can not more than available");
            if (!valid_d) errorProviderUser.SetError(comboBoxTravelAgent, "Travel Agent can not be empty");
            return valid_a && valid_b && valid_c && valid_d;
        }

        void toolBarButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (isValidForm())
                {
                    m_ticketDeduction.m_code = textBoxUserCode.Text;
                    m_ticketDeduction.m_transactionDate = dateTimePickerDate.Value; ;
                    m_ticketDeduction.m_quantity = numericUpDownQuantity.Value;
                    m_ticketDeduction.m_travelAgent = (TravelAgent)comboBoxTravelAgent.SelectedItem;
                    m_ticketDeduction.m_ticketType = (TicketType)Enum.Parse(typeof(TicketType), comboBoxTicketType.Text);
                    m_ticketDeduction.m_remark = textBoxREmark.Text;

                    //--------------
                    if (m_ticketDeduction.m_deductID > 0)
                    {
                        m_ticketDeduction.m_modfctnBy = m_current_user.UserID;
                        m_ticketDeductionService.UpdateTicketDeduction(m_ticketDeduction);
                    }
                    else
                    {
                        m_ticketDeduction.m_cretnBy = m_current_user.UserID;
                        m_ticketDeductionService.InserTicketDeduction(m_ticketDeduction);
                    }
                    m_parentForm.LoadAllTicketDeduction();
                  //  MessageBox.Show("Record has been saved.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    MessageBox.Show("Record has been saved [" + m_ticketDeduction.m_code + "].", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, new EventHandler(closeForm));
                    //clearForm();
                    //loadAllUser();
                    //setEditMode(EditMode.Saved);
                   // this.Close();
                }
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message, "Error Exception", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }

        }

        void closeForm(object sender, EventArgs e)
        {
            this.Close();
        }

        private void setEditMode(EditMode editMode)
        {
            toolBarButtonSave.Enabled = (editMode == EditMode.Create || editMode == EditMode.Edit || editMode == EditMode.Saved || editMode == EditMode.Delete)&& m_current_user.RoleDetails(this.Name).NewFlag;
            toolBarButtonEdit.Enabled = (editMode == EditMode.Load) && m_current_user.RoleDetails(this.Name).UpdateFlag;
            m_editmode = editMode;
            labelEditMode.Text = "[" + editMode + "]";
        }

        private void enableForm(bool enable)
        {
            textBoxUserCode.ReadOnly = !enable;
            //comboBoxTravelAgent.Enabled = enable && m_ticketDeduction.m_deductID == 0;
            comboBoxTravelAgent.Enabled = enable && (m_current_user.UserType == UserType.Administrators);
            numericUpDownQuantity.Enabled = enable;
            //numericUpDownTotalAmount.ReadOnly = !enable;
            textBoxREmark.Enabled = enable;
            comboBoxTicketType.Enabled = enable;
            dateTimePickerDate.Enabled = enable;

        }

        private void loadUser()
        {
            m_ticketDeduction.m_travelAgent = m_TravelAgentService.GetTravelAgentByID(m_ticketDeduction.m_travelAgent.TravelAgentID);

            textBoxUserCode.Text = m_ticketDeduction.m_code;
            comboBoxTravelAgent.Text = m_ticketDeduction.m_travelAgent.ToString();
            numericUpDownQuantity.Value = m_ticketDeduction.m_quantity;
            comboBoxTicketType.Text = m_ticketDeduction.m_ticketType.ToString();
            dateTimePickerDate.Value = m_ticketDeduction.m_transactionDate;
            textBoxREmark.Text = m_ticketDeduction.m_remark;
        }

        private void comboBoxTravelAgent_SelectedIndexChanged(object sender, EventArgs e)
        {
            timerUpdateBalance_Tick(sender, e);
        }
    }
}